package com.docking.heylo.service.impl;

import com.docking.heylo.dao.entity.Coupon;
import com.docking.heylo.dao.entity.CouponExample;
import com.docking.heylo.dao.mapper.CouponMapper;
import com.docking.heylo.enums.ECouponStatus;
import com.docking.heylo.exception.GeneralException;
import com.docking.heylo.service.ICouponService;
import com.docking.heylo.utils.HeyloMessageSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CouponServiceImpl implements ICouponService {

    @Resource
    private CouponMapper couponMapper;

    @Autowired
    private HeyloMessageSource ms;



    @Override
    public void use(int userId, String promoCode) {
        CouponExample example = new CouponExample();
        CouponExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(ECouponStatus.create.getValue());
        criteria.andPromoCodeEqualTo(promoCode);
        int row = couponMapper.updateByExampleSelective(new Coupon(){{
            setStatus(ECouponStatus.used.getValue());
        }},example);

        if(row != 1){
            throw new GeneralException(ms.getMessage("coupon.used"));
        }
    }

    @Override
    public void sendBack(int userId, String promoCode) {
        CouponExample example = new CouponExample();
        CouponExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(ECouponStatus.used.getValue());
        criteria.andPromoCodeEqualTo(promoCode);
        couponMapper.updateByExample(new Coupon(){{
            setStatus(ECouponStatus.create.getValue());
        }},example);
    }

    @Override
    public Coupon selectByPromoCode(String promoCode) {
        CouponExample example = new CouponExample();
        CouponExample.Criteria criteria = example.createCriteria();
        criteria.andPromoCodeEqualTo(promoCode);

        List<Coupon> coupons = couponMapper.selectByExample(example);
        return coupons.size() > 0 ? coupons.get(0) : null;
    }
}
